<template>
  <div style="margin-top: 50px">
    <el-form
      :model="value"
      ref="productAttrForm"
      label-width="150px"
      style="width: 720px"
      size="small"
    >
      <el-form-item label="属性类型：">
        <el-select
          v-model="value.productAttributeCategoryId"
          placeholder="请选择属性类型"
          @change="handleProductAttrChange"
        >
          <el-option
            v-for="item in productAttributeCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(productAttr, idx) in selectProductAttr" :key="idx">
            {{ productAttr.name }}：
            <!-- <el-checkbox-group v-if="productAttr.handAddStatus===0" v-model="selectProductAttr[idx].values">
              <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :label="item" :key="item"
                           class="littleMarginLeft"></el-checkbox>
            </el-checkbox-group> -->
            <div
              v-if="productAttr.handAddStatus === 0"
              style="display: flex; flex-wrap: wrap"
            >
              <div
                v-for="item in getInputListArr(productAttr.inputList)"
                :key="item"
                class="littleMarginLeft"
              >
                {{ item }}
              </div>
            </div>
            <div v-else>
              <!-- <el-checkbox-group v-model="selectProductAttr[idx].values">
                <div v-for="(item,index) in selectProductAttr[idx].options" style="display: inline-block"
                     class="littleMarginLeft">
                  <el-checkbox :label="item" :key="item"></el-checkbox>
                  <el-button type="text" class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx,index)">删除
                  </el-button>
                </div>
              </el-checkbox-group> -->
              <div style="display: flex; flex-wrap: wrap">
                <div
                  v-for="(item, index) in selectProductAttr[idx].options"
                  :key="index"
                  class="littleMarginLeft"
                  style="display: flex; margin-right: 20px; flex-wrap: wrap"
                >
                  <div>{{ item }}</div>
                  <el-button
                    type="text"
                    class="littleMarginLeft"
                    @click="handleRemoveProductAttrValue(idx, index)"
                    >删除</el-button
                  >
                </div>
              </div>

              <div>
                <el-input
                  v-model="productAttr.model"
                  style="width: 160px; margin-left: 10px"
                  clearable
                ></el-input>
                <el-button
                  class="littleMarginLeft"
                  @click="handleAddProductAttrValue(idx, productAttr.model)"
                  >增加</el-button
                >
              </div>
            </div>
          </div>
        </el-card>
        <el-table
          style="width: 100%; margin-top: 20px"
          :data="value.skuStockList"
          border
        >
          <el-table-column
            v-for="(item, index) in selectProductAttr"
            :label="item.name"
            :key="item.id"
            align="center"
          >
            <template slot-scope="scope">
              {{ getProductSkuSp(scope.row, index) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="value.productMajor == 2 ? '积分数量' : '商品价格'"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" width="80" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column
                  label="库存预警值"
                  width="80"
                  align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lowStock"></el-input>
            </template>
          </el-table-column> -->
          <el-table-column label="SKU编号" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuCode"></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="属性图片：" align="left">
            <template slot-scope="scope">
              <single-upload v-model="scope.row.pic"
                             style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleRemoveProductSku(scope.$index, scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          style="margin-top: 20px"
          @click="handleRefreshProductSkuList"
          >刷新列表
        </el-button>
        <el-button
          type="primary"
          style="margin-top: 20px"
          @click="handleSyncProductSkuPrice"
          >同步价格
        </el-button>
      </el-form-item>
      <!--<el-form-item label="属性图片：" v-if="hasAttrPic">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductAttrPics">
            <span>{{item.name}}:</span>
            <single-upload v-model="item.pic"
                           style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>
          </div>
        </el-card>
      </el-form-item>-->
      <!-- <el-form-item label="商品参数：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item,index) in selectProductParam" :class="{littleMarginTop:index!==0}">
            <div class="paramInputLabel">{{item.name}}:</div>
            <el-select v-if="item.inputType===1" class="paramInput" v-model="selectProductParam[index].value">
              <el-option
                      v-for="item in getParamInputList(item.inputList)"
                      :key="item"
                      :label="item"
                      :value="item">
              </el-option>
            </el-select>
            <el-input v-else class="paramInput" v-model="selectProductParam[index].value"></el-input>
          </div>
        </el-card>
      </el-form-item> -->
      <el-form-item label="商品相册：">
        <multi-upload v-model="selectProductPics"></multi-upload>
      </el-form-item>
      <el-form-item label="规格参数：">
        <!-- <tinymce
          :width="595"
          :height="300"
          v-model="value.detailMobileHtml"
        ></tinymce> -->

        <vue-ueditor-wrap
          v-model="value.detailMobileHtml"
          :config="myConfig"
        ></vue-ueditor-wrap>

        <!-- <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="电脑端详情" name="pc">
            <tinymce :width="595" :height="300" v-model="value.detailHtml"></tinymce>
          </el-tab-pane>
          <el-tab-pane label="移动端详情" name="mobile">
            <tinymce :width="595" :height="300" v-model="value.detailMobileHtml"></tinymce>
          </el-tab-pane>
        </el-tabs> -->
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev"
          >上一步，填写商品促销</el-button
        >
        <el-button type="primary" size="medium" @click="handleNext"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import VueUeditorWrap from "vue-ueditor-wrap";

import { fetchList as fetchProductAttrCateList } from "@/api/productAttrCate";
import { fetchList as fetchProductAttrList } from "@/api/productAttr";
import SingleUpload from "@/components/Upload/singleUpload";
import MultiUpload from "@/components/Upload/multiUpload";
import Tinymce from "@/components/Tinymce";

export default {
  name: "ProductAttrDetail",
  components: { SingleUpload, MultiUpload, Tinymce, VueUeditorWrap },
  props: {
    value: Object,
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ruleForm: {
        content: "",
      },
      /* ueditor */
      myConfig: {
        // serverUrl: `${__GATEWAYPATH__}/ueditor/ueditorConfig`, // 上传功能的后端服务器接口地址
        UEDITOR_HOME_URL: "/static/UEditor/", // 你的UEditor资源存放的路径,相对于打包后的index.html
        autoHeightEnabled: false, // 编辑器是否自动被内容撑高
        autoFloatEnabled: false, // 工具栏是否可以浮动
        initialFrameHeight: 340, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器高度
        enableAutoSave: true, // 关闭自动保存
      },

      typeId: "",
      //编辑模式时是否初始化成功
      hasEditCreated: false,
      //商品属性分类下拉选项
      productAttributeCategoryOptions: [],
      //选中的商品属性
      selectProductAttr: [],
      //选中的商品参数
      selectProductParam: [],
      //选中的商品属性图片
      selectProductAttrPics: [],
      //可手动添加的商品属性
      addProductAttrValue: "",
      addProductAttrValue1: "",
      //商品富文本详情激活类型
      activeHtmlName: "pc",
    };
  },
  computed: {
    //是否有商品属性图片
    hasAttrPic() {
      if (this.selectProductAttrPics.length < 1) {
        return false;
      }
      return true;
    },
    //商品的编号
    productId() {
      return this.value.id;
    },
    //商品的主图和画册图片
    selectProductPics: {
      get: function () {
        let pics = [];
        if (
          this.value.pic === undefined ||
          this.value.pic == null ||
          this.value.pic === ""
        ) {
          return pics;
        }
        pics.push(this.value.pic);
        if (
          this.value.albumPics === undefined ||
          this.value.albumPics == null ||
          this.value.albumPics === ""
        ) {
          return pics;
        }
        let albumPics = this.value.albumPics.split(",");
        for (let i = 0; i < albumPics.length; i++) {
          pics.push(albumPics[i]);
        }
        return pics;
      },
      set: function (newValue) {
        if (newValue == null || newValue.length === 0) {
          this.value.pic = null;
          this.value.albumPics = null;
        } else {
          this.value.pic = newValue[0];
          this.value.albumPics = "";
          if (newValue.length > 1) {
            for (let i = 1; i < newValue.length; i++) {
              this.value.albumPics += newValue[i];
              if (i !== newValue.length - 1) {
                this.value.albumPics += ",";
              }
            }
          }
        }
      },
    },
  },
  created() {
    this.getProductAttrCateList();
  },
  watch: {
    productId: function (newValue) {
      if (!this.isEdit) return;
      if (this.hasEditCreated) return;
      if (newValue === undefined || newValue == null || newValue === 0) return;
      this.handleEditCreated();
    },
  },
  methods: {
    handleEditCreated() {
      //根据商品属性分类id获取属性和参数
      if (this.value.productAttributeCategoryId != null) {
        this.handleProductAttrChange(this.value.productAttributeCategoryId);
      }
      this.hasEditCreated = true;
    },
    getProductAttrCateList() {
      let param = { pageNum: 1, pageSize: 100 };
      fetchProductAttrCateList(param).then((response) => {
        this.productAttributeCategoryOptions = [];
        let list = response.data.records;
        for (let i = 0; i < list.length; i++) {
          this.productAttributeCategoryOptions.push({
            label: list[i].name,
            value: list[i].id,
          });
        }
      });
    },
    getProductAttrList(type, cid) {
      let param = { pageNum: 1, pageSize: 3, type: type };
      fetchProductAttrList(cid, param).then((response) => {
        let list = response.data.records;
        if (type === 0) {
          this.selectProductAttr = [];
          for (let i = 0; i < list.length; i++) {
            let options = [];
            let values = [];
            if (this.isEdit) {
              if (list[i].handAddStatus === 1) {
                //编辑状态下获取手动添加编辑属性
                options = this.getEditAttrOptions(list[i].id);
              }
              //编辑状态下获取选中属性
              values = this.getEditAttrValues(i);
            }
            this.selectProductAttr.push({
              id: list[i].id,
              model:
                list[i].id == 422
                  ? this.addProductAttrValue
                  : this.addProductAttrValue1,
              name: list[i].name,
              handAddStatus: list[i].handAddStatus,
              inputList: list[i].inputList,
              values: values,
              options: options,
            });
          }
          if (this.isEdit) {
            //编辑模式下刷新商品属性图片
            this.refreshProductAttrPics();
          }
        } else {
          this.selectProductParam = [];
          for (let i = 0; i < list.length; i++) {
            let value = null;
            if (this.isEdit) {
              //编辑模式下获取参数属性
              value = this.getEditParamValue(list[i].id);
            }
            this.selectProductParam.push({
              id: list[i].id,
              name: list[i].name,
              value: value,
              inputType: list[i].inputType,
              inputList: list[i].inputList,
            });
          }
        }
      });
    },
    //获取设置的可手动添加属性值
    getEditAttrOptions(id) {
      let options = [];
      for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
        let attrValue = this.value.productAttributeValueList[i];
        if (attrValue.productAttributeId === id) {
          let strArr = attrValue.value.split(",");
          for (let j = 0; j < strArr.length; j++) {
            options.push(strArr[j]);
          }
          break;
        }
      }
      return options;
    },
    //获取选中的属性值
    getEditAttrValues(index) {
      let values = [];
      if (index === 0) {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          let sku = this.value.skuStockList[i];
          if (sku.sp1 != null && values.indexOf(sku.sp1) === -1) {
            values.push(sku.sp1);
          }
        }
      } else if (index === 1) {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          let sku = this.value.skuStockList[i];
          if (sku.sp2 != null && values.indexOf(sku.sp2) === -1) {
            values.push(sku.sp2);
          }
        }
      } else {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          let sku = this.value.skuStockList[i];
          if (sku.sp3 != null && values.indexOf(sku.sp3) === -1) {
            values.push(sku.sp3);
          }
        }
      }

      return values;
    },
    //获取属性的值
    getEditParamValue(id) {
      for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
        if (id === this.value.productAttributeValueList[i].productAttributeId) {
          return this.value.productAttributeValueList[i].value;
        }
      }
    },
    handleProductAttrChange(value) {
      this.typeId = value;
      this.getProductAttrList(0, value);
      this.getProductAttrList(1, value);
    },
    getInputListArr(inputList) {
      return inputList.split(",");
    },
    handleAddProductAttrValue(idx, model) {
      console.log(model, 9999);
      let options = this.selectProductAttr[idx].options;
      if (model == null || model == "") {
        this.$message({
          message: "属性值不能为空",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      if (options.indexOf(model) !== -1) {
        this.$message({
          message: "属性值不能重复",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      this.selectProductAttr[idx].options.push(model);
      this.selectProductAttr[idx].model = null;
    },
    handleRemoveProductAttrValue(idx, index) {
      console.log(idx);
      console.log(index);
      console.log(this.selectProductAttr);
      this.selectProductAttr[idx].options.splice(index, 1);
      console.log(this.selectProductAttr);
    },
    getProductSkuSp(row, index) {
      if (index === 0) {
        return row.sp1;
      } else if (index === 1) {
        return row.sp2;
      } else {
        return row.sp3;
      }
    },
    handleRefreshProductSkuList() {
      this.$confirm("刷新列表将导致sku信息重新生成，是否要刷新", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // this.refreshProductAttrPics();
        this.refreshProductSkuList();
      });
    },
    handleSyncProductSkuPrice() {
      this.$confirm("将同步第一个sku的价格到所有sku,是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (
          this.value.skuStockList !== null &&
          this.value.skuStockList.length > 0
        ) {
          let price = this.value.skuStockList[0].price;
          for (let i = 0; i < this.value.skuStockList.length; i++) {
            this.value.skuStockList[i].price = price;
          }
        }
      });
    },
    refreshProductSkuList() {
      debugger;
      this.value.skuStockList = [];
      let skuList = this.value.skuStockList;
      console.log(this.selectProductAttr);
      //只有一个属性时
      if (this.selectProductAttr.length === 1) {
        let values = this.selectProductAttr[0].options;
        for (let i = 0; i < values.length; i++) {
          skuList.push({
            sp1: values[i],
          });
        }
      } else if (this.selectProductAttr.length === 2) {
        let values0 = this.selectProductAttr[0].options;
        let values1 = this.selectProductAttr[1].options;
        if (values1.length === 0) {
          for (let i = 0; i < values0.length; i++) {
            skuList.push({
              sp1: values0[i],
              sp2: "",
            });
          }
        } else if (values0.length == 0) {
          for (let i = 0; i < values1.length; i++) {
            skuList.push({
              sp1: "",
              sp2: values1[i],
            });
          }
        } else {
          for (let i = 0; i < values0.length; i++) {
            for (let j = 0; j < values1.length; j++) {
              skuList.push({
                sp1: values0[i],
                sp2: values1[j],
              });
            }
          }
        }
      } else {
        let values0 = this.selectProductAttr[0].options;
        let values1 = this.selectProductAttr[1].options;
        let values2 = this.selectProductAttr[2].options;

        if (values0.length == 0) {
          if (values1.length == 0) {
            values2.some((item, index, values2) => {
              skuList.push({
                sp3: item,
              });
            });
          } else if (values2.length == 0) {
            values1.some((item1, index1, values1) => {
              skuList.push({
                sp2: item1,
              });
            });
          } else {
            values1.some((item1, index1, values1) => {
              values2.some((item2, index2, values2) => {
                skuList.push({
                  sp2: item1,
                  sp3: item2,
                });
              });
            });
          }
        } else if (values1.length == 0) {
          if (values0.length == 0) {
            values2.some((item, index, values2) => {
              skuList.push({
                sp3: item,
              });
            });
          } else if (values2.length == 0) {
            values0.some((item0, index0, values0) => {
              skuList.push({
                sp1: item0,
              });
            });
          } else {
            values0.some((item0, index0, values0) => {
              values2.some((item2, index2, values2) => {
                skuList.push({
                  sp1: item0,
                  sp3: item2,
                });
              });
            });
          }
        } else if (values2.length == 0) {
          if (values0.length == 0) {
            values1.some((item1, index1, values1) => {
              skuList.push({
                sp2: item1,
              });
            });
          } else if(values1.length == 0){
            values0.some((item0, index0, values0) => {
              skuList.push({
                sp1: item0,
              });
            });
          }else {
            values0.some((item0, index0, values0) => {
              values1.some((item1, index1, values1) => {
                skuList.push({
                  sp1: item0,
                  sp2: item1,
                });
              });
            });
          }
        } else {
          values0.some((item0, index0, values0) => {
            values1.some((item1, index1, values1) => {
              values2.some((item2, index2, values2) => {
                skuList.push({
                  sp1: item0,
                  sp2: item1,
                  sp3: item2,
                });
              });
            });
          });
        }
      }
    },
    refreshProductAttrPics() {
      this.selectProductAttrPics = [];
      if (this.selectProductAttr.length >= 1) {
        let values = this.selectProductAttr[0].values;
        for (let i = 0; i < values.length; i++) {
          let pic = null;
          if (this.isEdit) {
            //编辑状态下获取图片
            pic = this.getProductSkuPic(values[i]);
          }
          this.selectProductAttrPics.push({ name: values[i], pic: pic });
        }
      }
    },
    //获取商品相关属性的图片
    getProductSkuPic(name) {
      for (let i = 0; i < this.value.skuStockList.length; i++) {
        if (name === this.value.skuStockList[i].sp1) {
          return this.value.skuStockList[i].pic;
        }
      }
      return null;
    },
    //合并商品属性
    mergeProductAttrValue() {
      this.value.productAttributeValueList = [];
      for (let i = 0; i < this.selectProductAttr.length; i++) {
        let attr = this.selectProductAttr[i];
        if (
          attr.handAddStatus === 1 &&
          attr.options != null &&
          attr.options.length > 0
        ) {
          this.value.productAttributeValueList.push({
            productAttributeId: attr.id,
            name: attr.name,
            type: 1,
            value: this.getOptionStr(attr.options),
          });
        }
      }
      for (let i = 0; i < this.selectProductParam.length; i++) {
        let param = this.selectProductParam[i];
        this.value.productAttributeValueList.push({
          productAttributeId: param.id,
          name: param.name,
          type: 2,
          value: param.value,
        });
      }
    },
    //合并商品属性图片
    mergeProductAttrPics() {
      for (let i = 0; i < this.selectProductAttrPics.length; i++) {
        for (let j = 0; j < this.value.skuStockList.length; j++) {
          if (
            this.value.skuStockList[j].sp1 ===
            this.selectProductAttrPics[i].name
          ) {
            this.value.skuStockList[j].pic = this.selectProductAttrPics[i].pic;
          }
        }
      }
    },
    getOptionStr(arr) {
      let str = "";
      for (let i = 0; i < arr.length; i++) {
        str += arr[i];
        if (i != arr.length - 1) {
          str += ",";
        }
      }
      return str;
    },
    handleRemoveProductSku(index, row) {
      let list = this.value.skuStockList;
      console.log(list);
      if (list.length === 1) {
        list.pop();
      } else {
        list.splice(index, 1);
      }
      console.log(list);
    },
    getParamInputList(inputList) {
      return inputList.split(",");
    },
    handlePrev() {
      this.$emit("prevStep");
    },
    handleNext() {
      this.mergeProductAttrValue();
      this.mergeProductAttrPics();
      console.log(321321);
      this.$emit("finishCommit", this.isEdit);
      // this.$emit('nextStep')
    },
  },
};
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
